package com.wu.upload.controller;

import com.wu.upload.Exception.FileUploadException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Author Create by wuyanshen
 * @Date 2018-08-06 上午10:35
 * @Description <描述>
 */

@Controller
@RequestMapping("/")
public class FileUploadController {

    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file")MultipartFile file, HttpSession session, Model model) throws IOException {

        String name = file.getOriginalFilename();
        String newName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+
                new Random().nextInt(100)+name.substring(name.indexOf("."));

        String path = session.getServletContext().getRealPath("/WEB-INF/upload")+"/"+newName;
        try {
            file.transferTo(new File(path));
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("文件上传失败");
        }
        model.addAttribute("path",path);
        model.addAttribute("fileName",newName);
        return "success";
    }

    @RequestMapping("/downloadFile")
    public void downloadFile(String path,String fileName, OutputStream outputStream, HttpServletResponse response){
        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        try {
            StreamUtils.copy(new FileInputStream(path),outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/myfile")
    @ResponseBody
    public User myfile(){
        return new User("bob","123");
    }
}
